package top.lyc829.iot_server.service.impl;

import org.springframework.stereotype.Service;
import top.lyc829.iot_server.bean.User;
import top.lyc829.iot_server.service.AccessLogService;
import top.lyc829.iot_server.service.NfcService;
import top.lyc829.iot_server.service.UserService;
import top.lyc829.iot_server.utils.MqttUtil;
import top.lyc829.iot_server.utils.Result;
import top.lyc829.iot_server.utils.UserContainer;

import javax.annotation.Resource;

@Service
public class NfcServiceImpl implements NfcService {

    @Resource
    private UserService userService;
    @Resource
    private AccessLogService accessLogService;

    @Resource
    private UserContainer userContainer;

    private MqttUtil mqttUtil;

    public NfcServiceImpl(){
        mqttUtil = MqttUtil.build();
    }

    @Override
    public String open(String id) {
        User user = userService.findUserByNfcId(id);
        if (user == null){
            // 开门失败
            accessLogService.add(-1,0,id,0);
            return null;
        }else {
            // 开门成功
            accessLogService.add(user.getId(),0,id,1);
            return user.getName();
        }
    }

    @Override
    public Result getNfc(int userId) {
        User user = userService.findUserById(userId);
        if (user == null) {
            return Result.fail("该用户不存在");
        }
        user.setPassword("******");
        return Result.success(user);
    }

    @Override
    public Result deleteNfc(User user) {

        User user2 = userService.findUserById(user.getId());
        if (user2 == null) {
            return Result.fail("用户不存在");
        }
        user2.setNfcId(null);
        userService.updateUser(user2);

        return Result.success();
    }

    @Override
    public Result addNfc(Integer id) {

        User user = userService.findUserById(id);
        if (user == null) {
            return Result.fail("该用户不存在");
        }

        //TODO: 发送mqtt请求添加nfc
        //userService.updateUser(user);
        userContainer.setUser(user);
        mqttUtil.publish("/client/add_card","");

        return Result.success();
    }

}
